package com.dmc.util.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 二维码工具类
 */
public class QrCodeUtils {

    /**
     * 生成二维码
     */
    public static void createQREncode(HttpServletResponse res, String content, Integer width, Integer height){
        String format = "png";
        width = width == null ? 300 : width;
        height = height == null ? 300 : height;
        if(StringUtils.isNotBlank(content)){
            ServletOutputStream stream = null;
            try {
                //定义二维码的参数
                HashMap hints = new HashMap();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
                hints.put(EncodeHintType.MARGIN, 2);
                //生成二维码
                stream = res.getOutputStream();
                BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height , hints);
                MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(stream != null){
                    try {
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
    }
}
